package com.druid.app.dao.impl;

import com.druid.app.dao.StudentDao;
import com.druid.app.model.Student;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.List;

@Repository("studentDao")
public class StudentDaoImpl implements StudentDao {
    @Resource
    private SessionFactory sessionFactory;
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Student findStudentByStuId(String stuId) {
        Session session = sessionFactory.openSession();
        CriteriaBuilder builder = session.getCriteriaBuilder();
        CriteriaQuery<Student> criteriaQuery = builder.createQuery(Student.class);
        //criteriaQuery 对象可以添加各种查询条件和关联条件等等
        Root<Student> root = criteriaQuery.from(Student.class);
        criteriaQuery.select(root).where(builder.equal(root.get("stuId"),"10000001"));
        List<Student> list = session.createQuery(criteriaQuery).getResultList();
        if(list!= null && list.size()>0){
            return  list.get(0);
        }
        return null;
    }
    public Student save(Student o) {
        // TODO Auto-generated method stub
        Session session = sessionFactory.openSession();
        //开启事务
        Transaction tx = session.beginTransaction();
        session.save(o);
        tx.commit();
        return o;
    }

}
